const layout = {
  namespaced: true,
  state: {
    CurrentPage: {
      path: "",
      breadcrumbs: [],
    },
    pageBarShow: true,
    pageTags: [],
    // keepLive缓存
    cachePages: [],
  },
  mutations: {
    // 保存当前页面路由信息
    setActivePath(state, routerInfo) {
      state.CurrentPage.path = routerInfo.path;
      state.CurrentPage.breadcrumbs = routerInfo.breadcrumbs;
    },
    // 加入缓存
    addCachePage (state, pageName) {
      state.cachePages.push(pageName);
    },
    // 删除缓存
    delCachePage (state, pageName) {
      state.cachePages = state.cachePages.filter(item => {
        return item != pageName;
      });
      console.log('state.cachePages',state.cachePages)
    },
    // 添加页面标签
    addPageTag(state, tag) {
      state.pageTags.push(tag);
    },
    // 关闭页面标签
    closePageTag(state, index) {
      state.pageTags.splice(index, 1);
    },
    closeOtherTag(state, path) {
      let cuted = state.pageTags.filter((item) => {
        return path === item.path;
      });
      let _cachePages = [];
      cuted.forEach(item => {
        _cachePages.push(item.name);
      });
      state.pageTags = cuted;
      state.cachePages = _cachePages;
    },
    closeLeftTag(state, index) {
      let deletedList = state.pageTags.splice(0, index);
      // deletedList.forEach(item => {
      //   this.commit("Layout/delCachePage", item.name);
      // });
    },
    closeRightTag(state, index) {
      let deletedList = state.pageTags.splice(index + 1);
      // deletedList.forEach(item => {
      //   this.commit("Layout/delCachePage", item.name);
      // });
    },
    closeAllTag(state) {
      state.pageTags = [];
      state.cachePages = [];
    },
  },
  actions: {
    saveActivePage({ state, commit }, matched) {
      let breadcrumbs = [];
      matched.forEach((item) => {
        // 提取CurrentPage -> 当前页面路径  &  面包屑
        let { meta, path } = item;
        if (meta.title) {
          breadcrumbs.push({ meta, path });
        }
      });
      //  当前页面route
      let CurrentRoute = matched[matched.length - 1];
      commit("setActivePath", { path: CurrentRoute.path, breadcrumbs });

      // 提取pageTags
      let pageTags = state.pageTags;
        if (CurrentRoute.meta && !CurrentRoute.meta.notKeep) {
          // 将页面加入缓存
          commit("addCachePage", CurrentRoute.name);
        }

      let { name, meta, path } = CurrentRoute;
      if (path === "/dashbord") return;
      let findIndex = false;
      pageTags.forEach((item) => {
        if (item.path == path) {
          findIndex = true;
          return;
        }
      });
      findIndex ? "" : commit("addPageTag", { name, meta, path });
    },
  },
};
export default layout;
